/**
 * Copyright 2005 The Apache Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.edi.util;

import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Properties;

import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.edi.db.cfg.Environment;

/**
 * 用于搜寻上下文获取配置JNDI
 * 
 */
public final class NamingHelper {

	private static final Log log = LogFactory.getLog(NamingHelper.class);

	public static InitialContext getInitialContext(Properties props) {
		try {
			Hashtable hash = getJndiProperties(props);
			log.info("JNDI InitialContext properties:" + hash);
			try {
				return hash.size() == 0 ? new InitialContext()
						: new InitialContext(hash);
			} catch (NamingException e) {
				log.error("Could not obtain initial context", e);
				throw e;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

	}

	/**
	 * 根据Environment中用户配置好的edidb.jndi.* 配置JNDI
	 * 
	 * @param props
	 * @return
	 */
	public static Properties getJndiProperties(Properties props) {
		Properties result = new Properties();
		try {
			HashSet specialProps = new HashSet();
			//			specialProps.add(Environment.JNDI_CLASS);
			//			specialProps.add(Environment.JNDI_URL); 
			Iterator iter = props.keySet().iterator();
			while (iter.hasNext()) {
				String prop = (String) iter.next();
				if (prop.indexOf(Environment.JNDI_PREFIX) > -1
						&& specialProps.contains(prop)) {
					result.setProperty(prop.substring(Environment.JNDI_PREFIX
							.length() + 1), props.getProperty(prop));
				}
			}
			//			String jndiClass=props.getProperty(Environment.JNDI_CLASS);
			//			String jndiURL=props.getProperty(Environment.JNDI_URL);
			//			if (jndiClass != null) result.put(Context.INITIAL_CONTEXT_FACTORY, jndiClass);
			//			if (jndiURL != null) result.put(Context.PROVIDER_URL, jndiURL); 
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

}
